/*
 * Copyright (c) 2003 Apple Computer, Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * Copyright (c) 1999-2003 Apple Computer, Inc.  All Rights Reserved.
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/* ====================================================================
 * Copyright (c) 1995-1999 The Apache Group.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the Apache Group
 *    for use in the Apache HTTP server project (http://www.apache.org/)."
 *
 * 4. The names "Apache Server" and "Apache Group" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the Apache Group
 *    for use in the Apache HTTP server project (http://www.apache.org/)."
 *
 * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE APACHE GROUP OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Group and was originally based
 * on public domain software written at the National Center for
 * Supercomputing Applications, University of Illinois, Urbana-Champaign.
 * For more information on the Apache Group and the Apache HTTP server
 * project, please see <http://www.apache.org/>.
 *
 */

/* Base64 encoder/decoder. Originally Apache file ap_base64.c
 */

#include <string.h>
#include "common_base64.h"
#include "common_dbg_log.h"
#include "openssl/aes.h"

/* aaaack but it's fast and const should make it shared text page. */
static const RB_UINT8 g_szBase64Decode[256] =
{
    /* ASCII table */
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
    64,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64,
    64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64
};

static const RB_INT8 g_szBase64Encode[] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

RB_INT32 Base64_decode_len(const RB_INT8 *cBufCoded)
{
    RB_INT32 iBytesDecoded = 0;
    register const RB_UINT8 *pBufIn = RB_NULL;
    register RB_INT32 iNprBytes = 0;

    pBufIn = (const RB_UINT8 *) cBufCoded;
    while (g_szBase64Decode[*(pBufIn++)] <= 63);
    iNprBytes = (pBufIn - (const RB_UINT8 *)cBufCoded) - 1;
    iBytesDecoded = ((iNprBytes + 3) / 4) * 3;

    return iBytesDecoded + 1;
}

RB_INT32 Base64_decode(RB_INT8 *pBufPlain, const RB_INT8 *pBufCoded)
{
    RB_INT32 iBytesDecoded = 0;
    register const RB_UINT8 *pBufIn = RB_NULL;
    register RB_UINT8 *pBufOut = RB_NULL;
    register RB_INT32 iNprBytes = 0;

    pBufIn = (const RB_UINT8 *) pBufCoded;
    while (g_szBase64Decode[*(pBufIn++)] <= 63);
    iNprBytes = (pBufIn - (const RB_UINT8 *) pBufCoded) - 1;
    iBytesDecoded = ((iNprBytes + 3) / 4) * 3;

    pBufOut = (RB_INT8 *) pBufPlain;
    pBufIn = (const RB_UINT8 *) pBufCoded;

    while (iNprBytes > 4)
    {
        *(pBufOut++) =
            (RB_UINT8) (g_szBase64Decode[*pBufIn] << 2 | g_szBase64Decode[pBufIn[1]] >> 4);
        *(pBufOut++) =
            (RB_UINT8) (g_szBase64Decode[pBufIn[1]] << 4 | g_szBase64Decode[pBufIn[2]] >> 2);
        *(pBufOut++) =
            (RB_UINT8) (g_szBase64Decode[pBufIn[2]] << 6 | g_szBase64Decode[pBufIn[3]]);
        pBufIn += 4;
        iNprBytes -= 4;
    }

    /* Note: (nprbytes == 1) would be an error, so just ingore that case */
    if (iNprBytes > 1) 
    {
        *(pBufOut++) =
            (RB_UINT8) (g_szBase64Decode[*pBufIn] << 2 | g_szBase64Decode[pBufIn[1]] >> 4);
    }
    if (iNprBytes > 2) 
    {
        *(pBufOut++) =
            (RB_UINT8) (g_szBase64Decode[pBufIn[1]] << 4 | g_szBase64Decode[pBufIn[2]] >> 2);
    }
    if (iNprBytes > 3) 
    {
        *(pBufOut++) =
            (RB_UINT8) (g_szBase64Decode[pBufIn[2]] << 6 | g_szBase64Decode[pBufIn[3]]);
    }

    *(pBufOut++) = '\0';
    iBytesDecoded -= (4 - iNprBytes) & 3;
    return iBytesDecoded;
}

RB_INT32 Base64_encode_len(RB_INT32 iLen)
{
    return ((iLen + 2) / 3 * 4) + 1;
}

RB_INT32 Base64encode(RB_INT8 *pEncoded, const RB_INT8 *pString, RB_INT32 iLen)
{
    RB_INT32 i = 0;
    RB_INT8 *p = RB_NULL;

    p = pEncoded;
    for (i = 0; i < iLen - 2; i += 3)
    {
        *p++ = g_szBase64Encode[(pString[i] >> 2) & 0x3F];
        *p++ = g_szBase64Encode[((pString[i] & 0x3) << 4) |
                        ((RB_INT32) (pString[i + 1] & 0xF0) >> 4)];
        *p++ = g_szBase64Encode[((pString[i + 1] & 0xF) << 2) |
                        ((RB_INT32) (pString[i + 2] & 0xC0) >> 6)];
        *p++ = g_szBase64Encode[pString[i + 2] & 0x3F];
    }
    if (i < iLen)
    {
        *p++ = g_szBase64Encode[(pString[i] >> 2) & 0x3F];
        if (i == (iLen - 1)) 
        {
            *p++ = g_szBase64Encode[((pString[i] & 0x3) << 4)];
            *p++ = '=';
        }
        else 
        {
            *p++ = g_szBase64Encode[((pString[i] & 0x3) << 4) |
                            ((RB_INT32) (pString[i + 1] & 0xF0) >> 4)];
            *p++ = g_szBase64Encode[((pString[i + 1] & 0xF) << 2)];
        }
        *p++ = '=';
    }

    *p++ = '\0';
    return p - pEncoded;
}

/**************************************************************************************
 *Function: int pkcs7_padding(char *data, int dataSize, int dataLen)
 *Describe: pkcs7填充
 *Param   : data    : 数据
 *          dataSize: 存储 data的数组容量, 要补码，需要大于datalen
 *          dataLen : data 字符串长度
 *return  ：-1 data数据为空
 *          -2 填充后的数据越界
 *          >0 填充后的数据长度
 ***************************************************************************************/
RB_INT32 Pkcs7_padding(RB_UINT8 *data, RB_INT32 dataSize, RB_INT32 dataLen)
{
    RB_UINT8 paddingNum = 0;

	if(dataLen <= 0)
    {
        return RB_ERR;
    }
		
	if((dataLen+17) >= dataSize)
    {
        return RB_ERR;
    }
	
	paddingNum = 16 - (dataLen % 16);
	memset(&data[dataLen], paddingNum, paddingNum);
	data[dataLen+paddingNum] = '\0';
	
	return dataLen+paddingNum;
 
}
 
/**************************************************************************************
 *Function: int pkcs7_cuttingg(char *data, int dataLen)
 *Describe: pkcs7去除填充
 *Param   : data    : 数据
 *          dataLen : data 的长度
 *return  ：-1 data数据为空
 *          -3 填充检查失败
 *          >0 填充后的数据长度
 ***************************************************************************************/
RB_INT32 Pkcs7_cuttingg(RB_UINT8 *data, RB_INT32 dataLen)
{
    RB_INT32 i;
    RB_UINT8 paddingNum = 0;
	if(dataLen <= 0)
		return -1;
	
	paddingNum = data[dataLen-1];
	
	//check
	for(i=0;i<paddingNum;i++)
	{
		if(data[dataLen-paddingNum+i] != paddingNum)
			return -3;
	}
	
	memset(&data[dataLen-paddingNum], 0, paddingNum);
	data[dataLen-paddingNum] = '\0';
	
	return dataLen-paddingNum;
}

/**************************************************************************************
 *Function: AES128_CBC_Pkcs7_Decrypt(RB_UINT8 *aesKey, RB_UINT8 *ivec, RB_UINT8 *encrydata, RB_INT32 encrylen, RB_UINT8 *decdata, RB_UINT32 *declen)
 *Describe:  运算模式：CBC  填充模式：PKCS7 
 *Param   : aesKey    : 秘钥数据
 *          ivec        : iv向量
 *          encrydata : 加密的数据
 *          encrylen : 加密数据长度
 *          decdata : 解密后的数据
 *          declen : decdata的大小
 *return  ：解密后的数据长度，declen大小要大于这个值
 ***************************************************************************************/
RB_INT32 AES128_CBC_Pkcs7_Decrypt(const RB_UINT8 *aesKey, const RB_UINT8 *ivec, RB_UINT8 *encrydata, RB_INT32 encrylen, RB_UINT8 *decdata, RB_INT32 declen)
{
    AES_KEY key;
    RB_INT32 iLen = 0;
    RB_UINT8 ivec_copy[17] = {0};
    RB_UINT8 aesKey_copy[17] = {0};

    memcpy(ivec_copy, ivec, 16);
    memcpy(aesKey_copy, aesKey, 16);
    
    if((0 != encrylen % 16) || (declen < encrylen))
    {
        DBG_LOG_ERR("len err\n");
        return RB_ERR;
    }

    if(AES_set_decrypt_key(aesKey_copy, 128, &key) < 0)
    {
        DBG_LOG_ERR("set key failed\n");
        return RB_ERR;
    } 
    

    AES_cbc_encrypt(encrydata, decdata, encrylen, &key, ivec_copy, AES_DECRYPT);
    iLen = Pkcs7_cuttingg(decdata, encrylen);

    return iLen;
}

/**************************************************************************************
 *Function: AES128_CBC_Pkcs7_Encrypt(RB_UINT8 *aesKey, RB_UINT8 *ivec, RB_UINT8 *data, RB_UINT32 datalen, RB_UINT32 datasize, RB_UINT8 *encrydata, RB_INT32 encrylen)
 *Describe:  运算模式：CBC  填充模式：PKCS7 
 *Param   : aesKey    : 秘钥数据
 *          ivec        : iv向量
 *          data : 待加密的数据
 *          datalen : 待加密的数据长度
 *          datasize : 待加密数据容量，pkcs7补码需要
 *          encrydata : 加密后的数据
 *          encrylen ：encrydata的大小
 *return  ：加密后的数据长度，encrylen要大于这个值
 ***************************************************************************************/
RB_INT32 AES128_CBC_Pkcs7_Encrypt(const RB_UINT8 *aesKey, const RB_UINT8 *ivec, RB_UINT8 *data, RB_UINT32 datalen, RB_UINT32 datasize, RB_UINT8 *encrydata, RB_INT32 encrylen)
{
    AES_KEY key;
    RB_INT32 padnum = 0;
    RB_UINT8 ivec_copy[17] = {0};
    RB_UINT8 aesKey_copy[17] = {0};
    RB_UINT8 data_copy[1024] = {0};

    memcpy(ivec_copy, ivec, 16);
    memcpy(aesKey_copy, aesKey, 16);

    if(datasize > sizeof(data_copy))
    {
        DBG_LOG_ERR("data_copy len err\n");
        return RB_ERR;
    }

    memcpy(data_copy, data, datalen);

    if(AES_set_encrypt_key(aesKey_copy, 128, &key) < 0)
    {
        DBG_LOG_ERR("set key failed\n");
        return RB_ERR;
    }    

    padnum = Pkcs7_padding(data_copy, datasize, datalen);
    if(encrylen < padnum)
    {
        DBG_LOG_ERR("encrylen not enough\n");
        return RB_ERR;
    }    

    AES_cbc_encrypt(data_copy, encrydata, padnum, &key, ivec_copy, AES_ENCRYPT);
    return padnum;
}